package com.xh3140.xwidget.dialog.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.RecyclerView;

import com.xh3140.xwidget.dialog.params.ItemParams;

@SuppressWarnings("unused")
public class ItemView extends AppCompatCheckBox {
  private final boolean mIsRadio;

  private ItemView(@NonNull Context context) {
    this(context, true);
  }

  public ItemView(@NonNull Context context, boolean radio) {
    super(context);
    mIsRadio = radio;
    final int[] attrs = {mIsRadio ? android.R.attr.listChoiceIndicatorSingle : android.R.attr.listChoiceIndicatorMultiple};
    final TypedArray array = context.getTheme().obtainStyledAttributes(attrs);
    final Drawable drawable = array.getDrawable(0);
    array.recycle();
    setButtonDrawable(null);
    setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);
    setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
  }

  /**
   * 配置视图
   *
   * @param params 列表项目视图配置属性
   */
  public ItemView configView(@NonNull ItemParams params) {
    setChecked(params.checked);
    setText(params.text);
    setTextSize(params.textSize);
    setTextColor(params.textColor);
    setTypeface(getTypeface(), params.typeface);
    setGravity(params.gravity);
    if (params.pressedBackgroundColor == 0) {
      setBackgroundColor(params.backgroundColor);
    } else {
      setBackground(new RippleDrawable(ColorStateList.valueOf(params.pressedBackgroundColor),
              null, new ColorDrawable(params.backgroundColor)));
    }
    if (params.padding != null) {
      setPaddingRelative(params.padding[0], params.padding[1], params.padding[2], params.padding[3]);
    }
    if (params.callback != null) {
      params.callback.callback(this);
    }
    return this;
  }

  @Override
  public void toggle() {
    if (mIsRadio) {
      if (!isChecked()) {
        setChecked(true);
      }
    } else {
      setChecked(!isChecked());
    }
  }
}
